import axios from "axios";
import * as constant from "@/utils/constant.js";

// 图片上传
export async function uploadImg(file,url,isToken) {
    return new Promise(async (resolve, reject) => {
        // 给请求添加token,让后端识别当前微信用户
        const service = axios.create({
            baseURL: constant.API_BASE_URL,
            timeout: 1000 * 60 * 3,
            headers: {
                "Content-Type": "multipart/form-data",
            },
        });
        service.interceptors.request.use(
            (config) => {
                if (!isToken) {
                  return config
                }
                if (
                    config.url.indexOf("withoutLogin") == -1 ||
                    config.url.indexOf("bindAndLogin") == -1 ||
                    config.url.indexOf("listDept") == -1
                ) {
                    let token = uni.getStorageSync("token");
                    token && token !== "" && (config.headers.Authorization = "Bearer " + token);
                }
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );
        const formData = new FormData();
        formData.append("file", file);

        uni.showLoading({
            title: "图片上传中，请稍后···",
        });

        try {
            const response = await service({
                url:url?url: "/xsdcrm-wechat-api/common/upload",
                method: "POST",
                data: formData,
            })
            let res = response.data;
            uni.hideLoading();
            if (res.code !== 200) {
                uni.showToast({
                    title: res.msg,
                    icon: "error",
                });
                return;
            }
            resolve(res)
        } catch (e) {
            uni.hideLoading();
            uni.showToast({
                title: e,
                icon: "error",
            });
            reject(e)
        }
    })
}
